package com.otitan.la.forest.industry.utils;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import lombok.extern.slf4j.Slf4j;
import java.util.List;

/**
 * @Description: HttpClient 返回数据处理 工具类
 * @Author: jiachangsen
 * @CreateDate: 2020/10/15 11:11
 * @UpdateUser: jiachangsen
 * @UpdateDate: 2020/10/15 11:11
 * @UpdateRemark: 修改内容
 * @Version: 1.0
 */
@Slf4j
public class HttpResultUtil {

    /**
     * 获取 Obj data
     *
     * @param [dataStr]
     * @return com.alibaba.fastjson.JSONObject
     * @throws
     * @author jiachangsen
     * @date 2020/10/15 15:08
     */
    public static JSONObject getObjData(String dataStr) {
        if (StrUtil.isEmpty(dataStr)) {
            return null;
        }
        JSONObject jsonObject = JSONObject.parseObject(dataStr);
        int code = Integer.parseInt(jsonObject.getString("code"));
        if (code == 0) {
            return JSONObject.parseObject(jsonObject.getString("data"));
        }
        return null;
    }

    public static boolean getObjCode(String dataStr) {
        if (StrUtil.isEmpty(dataStr)) {
            return false;
        }
        JSONObject jsonObject = JSONObject.parseObject(dataStr);
        int code = Integer.parseInt(jsonObject.getString("code"));
        if (code == 0) {
            return true;
        }
        return false;
    }


    public static <T> T getObjData(String dataStr, Class<T> clazz) {
        JSONObject objData = getObjData(dataStr);
        if (CollUtil.isNotEmpty(objData)) {
            return JSONObject.parseObject(objData.toJSONString(), clazz);
        }
        return null;
    }

    /**
     * 获取 Arr data
     *
     * @param [dataStr]
     * @return com.alibaba.fastjson.JSONObject
     * @throws
     * @author jiachangsen
     * @date 2020/10/15 15:08
     */
    public static JSONArray getArrData(String dataStr) {
        if (StrUtil.isEmpty(dataStr)) {
            return null;
        }
        JSONObject jsonObject = JSONObject.parseObject(dataStr);
        int code = Integer.parseInt(jsonObject.getString("code"));
        if (code == 0) {
            return JSONArray.parseArray(jsonObject.getString("data"));
        }
        return null;
    }
    public static <T> List<T> getArrData(String dataStr, Class<T> clazz) {
        JSONArray objData = getArrData(dataStr);
        if (CollUtil.isNotEmpty(objData)) {
            return JSONArray.parseArray(objData.toJSONString(), clazz);
        }
        return null;
    }
}
